#!/usr/bin/env python
# -*- coding: utf-8 -*-

from email import Encoders
from email.Message import Message
from email.MIMEAudio import MIMEAudio
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.MIMEText import MIMEText
from email.Header import Header
import smtplib
import mimetypes
import time

import os
import sys
import getopt

def gmail_connect(user, passwd):
   server = smtplib.SMTP()
   print server.connect('smtp.gmail.com:587')
   print server.ehlo()
   print server.starttls()
   print server.ehlo()
   print server.login(user, passwd)
   return server

def gmail_close(server):
   server.close()

def set_header(subject, fr_addr, to_addr):
   msg = MIMEMultipart()
   msg['subject'] = Header(subject, 'utf-8')
   msg['to'] = to_addr
   msg['from'] = fr_addr
   msg['date']=time.ctime()
   msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
   msg.epilogue = ''

   return msg

def encode_file(path):
   fp = open(path, 'rb')
   data = MIMEText(fp.read(), _subtype='plain', _charset='utf-8')
   fp.close()

   return data

def encode_attach(path):
   filename = os.path.split(path)[1]
   ctype, encoding = mimetypes.guess_type(path)
   if ctype is None or encoding is not None:
       ctype = 'application/octet-stream'
   maintype, subtype = ctype.split('/', 1)
   if maintype == 'text':
       fp = open(path)
       data = MIMEText(fp.read(), _subtype=subtype)
       fp.close()
   elif maintype == 'image':
       fp = open(path, 'rb')
       data = MIMEImage(fp.read(), _subtype=subtype)
       fp.close()
   elif maintype == 'audio':
       fp = open(path, 'rb')
       data = MIMEAudio(fp.read(), _subtype=subtype)
       fp.close()
   else:
       fp = open(path, 'rb')
       data = MIMEBase(maintype, subtype)
       data.set_payload(fp.read())
       fp.close()
       # Encode the payload using Base64
       Encoders.encode_base64(data)
   data.add_header('Content-Disposition', 'attachment', filename=filename)

   return data

def sendmail(server, msg):
   str ='a'
   data = MIMEText(str, _subtype='plain', _charset='utf-8')
   msg.attach(data)

   server.sendmail(msg['from'], [msg['to']], msg.as_string())

def _usage():
 print '''usage: %s [-he:d] ...''' % os.path.basename(sys.argv[0])

def main(argv, user, passwd, to_addr='test@gmail.com'):
   try:
       opts, args = getopt.getopt(argv[1:], 'he:d', \
                                  ['help', 'eflags', 'dflags'])
   except getopt.GetoptError:
       print 'illegal option(s) -- ', str(argv[1:])
       sys.exit(1)

   eflags = dflags = False
   for o, a in opts:
       if o == '-h' or o == '--help':
           _usage()
           sys.exit(0)
       if o == '-e' or o == '--eflags':
           eflags = True
           to_addr = a
       if o == '-d' or o == '--dflags':
           dflags = True

   print 'Send to...:', to_addr
   server = gmail_connect(user, passwd)
   for arg in args:
       msg = set_header(arg, user+'@gmail.com', to_addr)
       if dflags == False:
           msg.attach(encode_file(arg))
           sendmail(server, msg)
           del msg
       else:
           if os.path.isfile(arg):
               msg.attach(encode_attach(arg))
               sendmail(server, msg)
               del msg
           if os.path.isdir(arg):
               for filename in os.listdir(arg):
                   path = os.path.join(arg, filename)
                   if not os.path.isfile(path):
                       continue
                   msg.attach(encode_attach(path))

               sendmail(server, msg)
               del msg
   gmail_close(server)

if __name__ == '__main__':
   main(sys.argv, 'login', 'passwd')

